<template>
  <page-header-wrapper>
    <a-card
      :bordered="false"
      title="详情">
      <div class="table-page-search-wrapper">
        <a-descriptions>
          <!-- <a-descriptions-item label="创建时间">
            {{ contractInfo.createDate }}
          </a-descriptions-item> -->
          <a-descriptions-item label="合同名称">
            {{ contractInfo.contractName }}
          </a-descriptions-item>
          <a-descriptions-item label="合同类型">
            {{ contractInfo.contractType === 2 ? '采购合同' : '项目合同' }}
          </a-descriptions-item>
          <a-descriptions-item label="甲方">
            {{ contractInfo.firstParty }}
          </a-descriptions-item>
          <a-descriptions-item label="甲方负责人">
            {{ contractInfo.firstPartyPerson }}
          </a-descriptions-item>
          <a-descriptions-item label="甲方联系方式">
            {{ contractInfo.firstPartyContactWay }}
          </a-descriptions-item>
          <a-descriptions-item label="乙方">
            {{ contractInfo.secondParty }}
          </a-descriptions-item>
          <a-descriptions-item label="乙方负责人">
            {{ contractInfo.secondPartyPerson }}
          </a-descriptions-item>
          <a-descriptions-item label="乙方联系人">
            {{ contractInfo.secondPartyContactWay }}
          </a-descriptions-item>
          <a-descriptions-item label="签订日期">
            {{ contractInfo.signDate }}
          </a-descriptions-item>
          <a-descriptions-item label="交付日期">
            {{ contractInfo.deliveryDate }}
          </a-descriptions-item>
          <a-descriptions-item label="合同总金额">
            {{ contractInfo.money }}
          </a-descriptions-item>
          <a-descriptions-item label="违约责任">
            {{ contractInfo.breachLiability }}
          </a-descriptions-item>
        </a-descriptions>
        <a-button
          type="primary"
          v-if="contractUpdate"
          @click="editContract">编辑</a-button>
        <!-- 编辑合同 -->
        <create-form
          ref="createModal"
          :suppliers="suppliers"
          :customers="customers"
          :isEdit="true"
          :visible="visible"
          :loading="confirmLoading"
          @cancel="editContractCancel"
          @ok="editContractOk" />
      </div>
    </a-card>
    <div
      class="table-operator"
      :style="{marginTop: '30px'}">
      <span style="font-size: 20px;font-weight: bold;padding: 10px;padding-right: 30px">合同附件</span>
      <a-button
        type="primary"
        icon="plus"
        v-if="fupdate"
        @click="addFile">新建</a-button>
      <a-spin :spinning="fileTabLoading">
        <a-table
          size="default"
          rowKey="fileId"
          :style="{marginTop: '50px', background: 'white'}"
          :columns="fileColumns"
          :dataSource="files"
          :pagination="false">
          <span
            slot="serial"
            slot-scope="text, record, index">
            {{ index + 1 }}
          </span>
          <span
            slot="fileDownload"
            slot-scope="text, record">
            <a
              :href="`${record.fileUrl}`"
              :download="record.fileName">{{ record.fileName }}</a>
          </span>
          <span
            slot="action"
            slot-scope="text, record">
            <template>
              <a
                @click="handleShowImg(record)">预览</a>
              <a-divider type="vertical" />
              <a
                v-if="fdelete"
                @click="handleDeleteFile(record)">删除</a>
            </template>
          </span>
        </a-table>
      </a-spin>
      <file-create-form
        ref="fileCreateForm"
        :fsave="fsave"
        :visible="fileCreateVisible"
        @cancel="handleFileCancel"
        @ok="handleFileOK" />
      <a-modal
        title="图片预览"
        width="800"
        :visible="showImg"
        :footer="null"
        @cancel="() => {this.showImg = false}">
        <div style="display: flex;justify-content: center">
          <img style="width: 700px" :src="imgUrl" />
        </div>
      </a-modal>
    </div>
    <product-list :contractInfo="this.contractInfo" />
    <income-list :contractInfo="this.contractInfo" @handleShowImg="handleShowImg"/>
  </page-header-wrapper>
</template>

<script>
import { updateContract, getFileByIds, supplierSelect, getContractInfo, getAllCustom } from '@/api/manage'
import { STable } from '@/components'
import CreateForm from './modules/CreateForm'
import FileCreateForm from './modules/FileCreateForm'
import ProductList from './modules/ProductList'
import IncomeList from './modules/IncomeList'
import { productColumns, fileColumns, incomeExpensesColumns } from './config'
import { message } from 'ant-design-vue'
import { mapGetters } from 'vuex'
import { isInMenu } from '../config'

export default {
  name: 'TableList',
  components: {
    STable,
    CreateForm,
    FileCreateForm,
    ProductList,
    IncomeList
    // ProductForm,
    // IncomeExpensesForm,
  },
  data () {
    this.productColumns = productColumns
    this.fileColumns = fileColumns
    this.incomeExpensesColumns = incomeExpensesColumns
    return {
      // 预览
      showImg: false,
      imgUrl: '',
      // 合同编辑
      contractUpdate: false,
      // 实际采购
      realBuySave: false,
      realBuyUpdate: false,
      realBuyDelete: false,
      // 实际采购
      planBuySave: false,
      planBuyUpdate: false,
      planBuyDelete: false,
      // 实际采购
      flist: false,
      fsave: false,
      fupdate: false,
      fdelete: false,
      // 路由跳转的 合同信息
      contractInfo: {},
      // 编辑合同
      visible: false,
      confirmLoading: false,
      conRecord: undefined,
      // 附件表
      files: undefined,
      fileTabLoading: false,
      fileCreateVisible: false,
      // 团队
      memberFormVisible: false,
      memberFormConfirmLoading: false,
      memberFormMdl: null,
      // 采购清单
      productFormVisible: false,
      productFormConfirmLoading: false,
      productFormMdl: null,
      // 任务管理
      incomeExpensesFormVisible: false,
      incomeExpensesFormConfirmLoading: false,
      incomeExpensesFormMdl: null,
      // 查询参数
      queryParam: {},
      staffInfo: {},
      selectedRowKeys: [],
      selectedRows: [],
      current: 0,
      steps: [
        {
          title: '签订合同',
          content: '由xxx签订合同，跟进项目需求。'
        },
        {
          title: '设备采购',
          content: '由xxx同事拟定采购计划，和相关供应商询价，确认供应商。'
        },
        {
          title: '系统开发',
          content: '由xxx同事作为项目经理，负责xxx系统的研发。'
        }
      ],
      suppliers: [],
      customers: []
    }
  },
  created () {
    // 合同编辑
    this.contractUpdate = isInMenu(this.menu, 'ROLE_but:contract:update')
    // 文件权限
    this.flist = isInMenu(this.menu, 'ROLE_but:contractFile:ids')
    this.fsave = isInMenu(this.menu, 'ROLE_but:contractFile:save')
    this.fupdate = isInMenu(this.menu, 'ROLE_but:contractFile:update')
    this.fdelete = isInMenu(this.menu, 'ROLE_but:contractFile:delete')
  },
  mounted () {
    this.getContract()
    this.conRecord = this.contractInfo
    supplierSelect({}).then(res => { this.suppliers = res.data })
    getAllCustom({}).then(res => { this.customers = res.data })
  },
  computed: {
    ...mapGetters(['menu']),
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    // 获取合同详情
    getContract () {
      const id = this.$route.query.contractId
      getContractInfo(id).then(res => {
        this.contractInfo = res.data
        this.conRecord = this.contractInfo
        this.getFiles(res.data)
      })
    },
    // 编辑合同
    editContract (event) {
      this.visible = true
      const form = this.$refs.createModal.form
      this.conRecord = this.contractInfo
      this.$nextTick(() => {
        form.setFieldsValue(this.contractInfo)
      })
    },
    editContractCancel () {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    editContractOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          updateContract(
            Object.assign({}, values, {
              fileIds: this.conRecord.fileIds,
              contractId: this.conRecord.contractId
              // signDate: this.conRecord.signDate,
              // deliveryDate: this.conRecord.deliveryDate
            })
          )
            .then(res => {
              // this.$refs.table.refresh()
              message.success('编辑成功')
              this.contractInfo = values
            })
            .finally(() => {
              this.visible = false
              this.$refs.createModal.resetFileList()
              form.resetFields()
              this.confirmLoading = false
              this.getContract()
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    // 附件
    getFiles (record) {
      if (record.fileIds) {
      this.fileTabLoading = true
      getFileByIds({ fileIds: record.fileIds })
        .then(res => {
          this.files = res.data
        })
        .finally(() => {
          this.fileTabLoading = false
        })
      } else {
        this.files = []
      }
    },
    addFile () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = true
    },
    handleDeleteFile (record) {
      let _fileIds = ''
      if (this.conRecord.fileIds) {
        const fids = this.conRecord.fileIds.split(',')
        const index = fids.indexOf(String(record.fileId))
        if (index > -1) {
          fids.splice(index, 1)
        }
        _fileIds = fids.join(',') || ''
        this.conRecord.fileIds = _fileIds
      }
      const params = {
        contractId: this.conRecord.contractId,
        fileIds: _fileIds,
        contractName: this.conRecord.contractName,
        contractType: this.conRecord.contractType,
        firstParty: this.conRecord.firstParty,
        firstPartyPerson: this.conRecord.firstPartyPerson,
        firstPartyContactWay: this.conRecord.firstPartyContactWay,
        secondParty: this.conRecord.secondParty,
        secondPartyPerson: this.conRecord.secondPartyPerson,
        secondPartyContactWay: this.conRecord.secondPartyContactWay,
        breachLiability: this.conRecord.breachLiability,
        signDate: this.conRecord.signDate,
        deliveryDate: this.conRecord.deliveryDate,
        money: this.conRecord.money,
        note: this.conRecord.note
      }
      updateContract(params)
        .then(res => {
          message.success('删除成功')
        })
        .finally(() => {
          this.fileCreateVisible = false
          this.$refs.createModal.resetFileList()
          this.getContract()
        })
    },
    handleFileCancel () {
      this.$refs.fileCreateForm.resetFileList()
      this.fileCreateVisible = false
    },
    handleFileOK () {
      const form = this.$refs.fileCreateForm.form
      form.validateFields((errors, values) => {
        if (!errors && values.fileIds) {
          const _fileIds = this.conRecord.fileIds ? this.conRecord.fileIds + ',' : ''
          const params = {
            contractId: this.conRecord.contractId,
            fileIds: _fileIds + values.fileIds,
            contractName: this.conRecord.contractName,
            contractType: this.conRecord.contractType,
            firstParty: this.conRecord.firstParty,
            firstPartyPerson: this.conRecord.firstPartyPerson,
            firstPartyContactWay: this.conRecord.firstPartyContactWay,
            secondParty: this.conRecord.secondParty,
            secondPartyPerson: this.conRecord.secondPartyPerson,
            secondPartyContactWay: this.conRecord.secondPartyContactWay,
            breachLiability: this.conRecord.breachLiability,
            signDate: this.conRecord.signDate,
            deliveryDate: this.conRecord.deliveryDate,
            money: this.conRecord.money,
            note: this.conRecord.note
          }
          updateContract(params)
            .then(res => {
              this.$refs.table.refresh()
            })
            .finally(() => {
              this.fileCreateVisible = false
              this.$refs.createModal.resetFileList()
              this.getContract()
            })
        }
      })
    },
    handleAdd () {
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleInfo () {},
    next () {
      this.current++
    },
    prev () {
      this.current--
    },
    // 团队成员
    memberAdd () {
      this.memberFormMdl = null
      this.memberFormVisible = true
    },
    // 采购清单
    productAdd () {
      this.productFormMdl = null
      this.productFormVisible = true
    },
    productEdit (record) {
      this.productFormVisible = true
      this.productFormMdl = { ...record }
    },
    productOk () {
      const form = this.$refs.productModal.form
      this.productFormConfirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
        } else {
          this.confirmLoading = false
        }
      })
    },
    productCancel () {
      this.productFormVisible = false

      const form = this.$refs.productModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    // 任务管理
    incomeExpensesAdd () {
      this.incomeExpensesFormMdl = null
      this.incomeExpensesFormVisible = true
    },
    tableCustomRow (record, index) {
      return {
        on: {
          click: event => {
            this.conRecord = record
            record.fileIds ? this.getFiles(record) : (this.files = [])
          }
        }
      }
    },
    handleShowImg (record) {
      this.showImg = true
      this.imgUrl = record?.fileUrl
    }
  }
}
</script>
<style scoped>
.steps-content {
  margin-top: 16px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  padding-top: 80px;
}

.steps-action {
  margin-top: 24px;
}
</style>
